// pages/login/login.js
import Message from 'tdesign-miniprogram/message/index';
import {
  baseUrl
} from '../../config/api'
Page({
  data: {
    mobile: '',
    password: '',
    captcha: '',       // 用户输入的验证码
    captchaImg: '',    // 验证码图片地址
    captchaUuid: ''    // 验证码 uuid  
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.refreshCaptcha()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },
  refreshCaptcha() {
    const uuid = Date.now().toString();
    this.setData({
      captchaUuid: uuid,
      captchaImg: baseUrl + '/captcha.jpg?uuid=' + uuid + '&ts=' + Date.now()
    });
  },  
  changeVal(e) {
    // 取出实时的变量值
    let value = e.detail.value;
    let fieldName = e.target.dataset.fieldName;
    this.setData({
      [`${fieldName}`]: value
    })
  },
  login() {
    if (this.data.password === '' || this.data.mobile === '') {
      Message.warning({
        context: this,
        offset: [20, 32],
        duration: 1500,
        icon: true,
        content: '手机号或密码不能为空',
      });
      return;
    }

      // 手机号格式校验
    if (!/^1[3-9]\d{9}$/.test(this.data.mobile)) {
      Message.warning({
        context: this,
        offset: [20, 32],
        duration: 1500,
        icon: true,
        content: '请输入正确的手机号',
      });
      return;
    }
    
    let _this = this
    wx.request({
      url: baseUrl + '/app/wx/login',
      method: 'POST',
      data: {
        mobile: this.data.mobile,
        password: this.data.password,
        code: this.data.captcha,       // 用户输入的验证码
        codeUUID: this.data.captchaUuid,   // 对应的 uuid
        fromWhere: "USER"
      },
      success: (res) => {
        if (res.data.code === 0) {
          Message.success({
            context: this,
            offset: [20, 32],
            duration: 1500,
            icon: true,
            content: "登录成功"
          });
          wx.setStorage({
            key: "userInfo",
            data: JSON.stringify(res.data.data)
          });
          wx.navigateBack();
        } else {
          Message.warning({
            context: this,
            offset: [20, 32],
            duration: 1500,
            icon: true,
            content: res.data.msg
          });
          this.refreshCaptcha(); // 登录失败刷新验证码
        }
      }
    });
  }

})